#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: twl
@date: 2022/5/9 11:03
@description:
"""
import datetime

from flask_sqlalchemy import SQLAlchemy

# 创建db对象
db = SQLAlchemy()


class BaseEntity(db.Model):
	__abstract__ = True
	id = db.Column(db.BigInteger, primary_key=True)
	log_time = db.Column(db.BigInteger)
	active_id = db.Column(db.String(50), nullable=False, server_default='')
	mac = db.Column(db.String(50), nullable=False, server_default='')
	log_id = db.Column(db.String(65), nullable=False, server_default='0')
	create_time = db.Column(db.DateTime, default=datetime.datetime.now())


	@staticmethod
	def save_batch(save_list):
		size = len(save_list)
		limit = 100
		if size > limit:
			chunk = int(size / limit)
			last = size % limit
			for i in range(0, chunk):
				sub_list = save_list[limit * i: limit * (i + 1)]
				db.session.bulk_save_objects(sub_list, return_defaults=True)
				try:
					db.session.commit()
				except Exception as e:
					db.session.rollback()
					db.session.close()
					raise e
			if last > 0:
				sub_list = save_list[limit * chunk: size]
				db.session.bulk_save_objects(sub_list, return_defaults=True)
				try:
					db.session.commit()
				except Exception as e:
					db.session.rollback()
					db.session.close()
					raise e
		else:
			db.session.bulk_save_objects(save_list, return_defaults=True)
			try:
				db.session.commit()
			except Exception as e:
				db.session.rollback()
				db.session.close()
				raise e

	@staticmethod
	def save(save_obj):
		db.session.add(save_obj)
		try:
			db.session.commit()
		except Exception as e:
			db.session.rollback()
			db.session.close()
			raise e

	def to_json(self):
		fields = self.__dict__
		if "_sa_instance_state" in fields:
			del fields["_sa_instance_state"]
		for key, value in fields.items():
			if isinstance(value, datetime.datetime):
				fields[key] = value.strftime('%Y-%m-%d %H:%M:%S')
			elif isinstance(value, datetime.time):
				fields[key] = value.isoformat()
			elif isinstance(value, datetime.timedelta):
				fields[key] = (
					datetime.datetime.min +
					value).time().isoformat()
		return fields
